package com.itcms.core.web.back;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foxinmy.weixin4j.token.TokenHolder;
import com.itcms.common.orm.LimitRequest;
import com.itcms.common.orm.Limitable;
import com.itcms.common.util.JacksonMapper;
import com.itcms.common.util.ReturnObj;
import com.itcms.common.web.PathResolver;
import com.itcms.common.web.Servlets;
import com.itcms.core.constant.Constants;
import com.itcms.core.domain.AttachmentRef;
import com.itcms.core.domain.Attribute;
import com.itcms.core.domain.Info;
import com.itcms.core.domain.InfoDetail;
import com.itcms.core.domain.InfoFile;
import com.itcms.core.domain.InfoImage;
import com.itcms.core.domain.Node;
import com.itcms.core.domain.User;
import com.itcms.core.html.HtmlService;
import com.itcms.core.service.AttachmentRefService;
import com.itcms.core.service.AttachmentService;
import com.itcms.core.service.AttributeService;
import com.itcms.core.service.InfoQueryService;
import com.itcms.core.service.InfoService;
import com.itcms.core.service.MemberGroupService;
import com.itcms.core.service.NodeQueryService;
import com.itcms.core.service.OperationLogService;
import com.itcms.core.service.UserService;
import com.itcms.core.support.Context;
import com.itcms.plug.domain.Company;
import com.itcms.plug.domain.Department;
import com.itcms.plug.domain.RecruitPlan;
import com.itcms.webservice.domain.InfoVO;

/**
 * InfoController
 * 
 * @author mengjie
 * 
 */
@Controller
@RequestMapping("/core/info")
public class InfoApiController {
	private static final Logger logger = LoggerFactory
			.getLogger(InfoApiController.class);

	public static final int INCLUDE_CHILDREN = 0;
	public static final int INCLUDE_MULTI = 1;
	public static final int MAIN_NODE = 2;
	
	private UserService userService;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	
	@RequestMapping("api/save.do")
	public String apiSave(com.itcms.webservice.domain.Info info, String password){
		String cateID = info.getCateID();
		String content = info.getContent();
		String expDate = info.getExpDate();
		String filesJsoin = info.getFilesJsoin();
		String lastUpdateDate = info.getLastUpdateDate();
		String lastUpdateUserId = info.getLastUpdateUserId();
		String lastUpdateUserName = info.getLastUpdateUserName();
		String publishedTime = info.getPublishedTime();
		String siteID = info.getSiteID();
		String source = info.getSource();
		String subTitle = info.getSubTitle();
		String templateId = info.getTemplateId();
		String title = info.getTitle();
		String type = info.getType();
		String url = info.getUrl();
		String writeDate = info.getWriteDate();
		String writer = info.getWriter();
		String writerName = info.getWriterName();
		
		InfoDetail detail = new InfoDetail();
		detail.setFullTitle(info.getTitle());
		detail.setLink(info.getUrl());
		detail.setMetaDescription(info.getSource());
		detail.setTitle(info.getTitle());
		
		Map<String, String> clobs = new HashMap<String, String>();
		clobs.put("text", content);
		String[] filesName = null; String[] filesFile = null; Long[] filesLength = null;
		HttpServletRequest request = null;
		apiSave(new Info(), detail, null, null, null, null, null, Integer.valueOf(cateID), null, false, 
				null, null, null, filesName, filesFile, filesLength, request);
		return null;
	}
	
	public String apiSave(Info bean, InfoDetail detail, Integer[] nodeIds,
			Integer[] specialIds, Integer[] viewGroupIds, Integer[] viewOrgIds,
			Integer[] attrIds, Integer nodeId, String tagKeywords,
			@RequestParam(defaultValue = "false") boolean draft,
			String[] imagesName, String[] imagesText, String[] imagesImage,
			String[] filesName, String[] filesFile, Long[] filesLength,
			HttpServletRequest request) {
		Integer siteId = Context.getCurrentSiteId();
		Integer userId = Context.getCurrentUserId();
		Map<String, String> customs = Servlets.getParamMap(request, "customs_");
		Map<String, String> clobs = Servlets.getParamMap(request, "clobs_");
		if (StringUtils.isBlank(detail.getMetaDescription())) {
			String title = detail.getTitle();
			detail.setMetaDescription(Info.getDescription(clobs, title));
		}
		String[] tagNames = splitTagKeywords(tagKeywords);
		Map<String, String> attrImages = Servlets.getParamMap(request,
				"attrImages_");
		for (Map.Entry<String, String> entry : attrImages.entrySet()) {
			entry.setValue(StringUtils.trimToNull(entry.getValue()));
		}
		List<InfoImage> images = new ArrayList<InfoImage>();
		if (imagesName != null) {
			InfoImage infoImage;
			for (int i = 0, len = imagesName.length; i < len; i++) {
				if (StringUtils.isNotBlank(imagesName[i])
						|| StringUtils.isNotBlank(imagesText[i])
						|| StringUtils.isNotBlank(imagesImage[i])) {
					infoImage = new InfoImage(imagesName[i], imagesText[i],
							imagesImage[i]);
					images.add(infoImage);
				}
			}
		}
		List<InfoFile> files = new ArrayList<InfoFile>();
		if (filesName != null) {
			InfoFile infoFile;
			for (int i = 0, len = filesFile.length; i < len; i++) {
				if (StringUtils.isNotBlank(filesName[i])
						&& StringUtils.isNotBlank(filesFile[i])) {
					infoFile = new InfoFile(filesName[i], filesFile[i],
							filesLength[i]);
					files.add(infoFile);
				}
			}
		}
		String status = draft ? Info.DRAFT : null;
		service.save(bean, detail, nodeIds, specialIds, viewGroupIds,
				viewOrgIds, customs, clobs, images, files, attrIds, attrImages,
				tagNames, nodeId, userId, status, siteId);
		String ip = Servlets.getRemoteAddr(request);
		logService.operation("opr.info.add", bean.getTitle(), null,
				bean.getId(), ip, userId, siteId);
		logger.info("save Info, title={}.", bean.getTitle());
		return ip;
	}
	
	@RequestMapping("api/list.do")
	@ResponseBody
	public ReturnObj<List<InfoVO>> apiList(
			Integer queryNodeId,
			Integer queryNodeType,
			Integer queryInfoPermType,
			String queryStatus,
			String queryNodeName,
			HttpServletRequest request) {
		List<InfoVO> list = new ArrayList<InfoVO>();
		queryNodeType = queryNodeType == null ? 0 : queryNodeType;
//		Integer siteId = Context.getCurrentSiteId();
//		User user = Context.getCurrentUser();
		Integer siteId = Context.getCurrentSiteId();
		User user = userService.findByUsername("admin");
		Integer nodeId = null;
		Integer mainNodeId = null;
		String treeNumber = null;
		Node queryNode = null;
		if (queryNodeId != null) {
			queryNode = nodeQuery.get(queryNodeId);
		}
		if (queryNodeName != null) {
			queryNode = nodeQuery.findByNumber(siteId, queryNodeName);
		}
		if (queryNode != null) {
			if (queryNodeType == INCLUDE_MULTI) {
				nodeId = queryNodeId;
			} else if (queryNodeType == MAIN_NODE) {
				mainNodeId = queryNodeId;
			} else {
				treeNumber = queryNode.getTreeNumber();
			}
		}
		Map<String, String[]> params = Servlets.getParamValuesMap(request,
				Constants.SEARCH_PREFIX);
		int infoPermType = user.getInfoPermType(siteId);
		if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
			infoPermType = queryInfoPermType;
		}
		boolean allInfoPerm = user.getAllInfoPerm(siteId);
		Sort sort = new Sort(Direction.DESC, "publishDate", "id");
		Limitable limit = LimitRequest.defaultSort(null, sort);
		List<Info> infos = query.findAll(siteId, mainNodeId, nodeId,
				treeNumber, user.getId(), allInfoPerm, infoPermType,
				queryStatus, params, limit);
		List<Map<String, String>> attachList = new ArrayList<Map<String, String>>();
		for (Info info : infos) {
			InfoVO infoVO = new InfoVO();
			infoVO.setContent(info.getClobs());
			infoVO.setId(info.getId());
			infoVO.setCateId(info.getNode().getId());
			infoVO.setSiteId(siteId);
			infoVO.setTitle(info.getDetail().getTitle());
			infoVO.setSubTitle(info.getSubtitle());
			infoVO.setUrl(info.getDetail().getLink());
			String publishDate = DateUtils.formatDate(info.getPublishDate(), "yyyy-MM-dd HH:mm:ss");
			infoVO.setPublishedTime(publishDate);
			infoVO.setWriteDate(publishDate);
			infoVO.setExpDate(publishDate);
			infoVO.setLastUpdateDate(publishDate);
			infoVO.setSource(info.getDetail().getMetaDescription());
			infoVO.setLastUpdateUsername("");
			infoVO.setLastUpdateUserId("");
			infoVO.setWriter(user.getId().toString());
			infoVO.setWriterName(user.getUsername());
			infoVO.setTemplateId(info.getTemplate());
			infoVO.setType(info.getStatus());
			infoVO.setPwd("gdjt2010");
			
			List<AttachmentRef> attachmentRefs = attachmentRefService.findByFtypeAndFid("info", user.getId());
			for (AttachmentRef attachmentRef : attachmentRefs) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("FileName", attachmentRef.getAttachment().getRealName());
				map.put("Url", attachmentRef.getAttachment().getName());
				attachList.add(map);
			}
			
			String fileJson = JacksonMapper.toJson(attachList);
			System.out.println(fileJson);
			
			infoVO.setFiles(info.getFiles());
			list.add(infoVO);
		}
		ReturnObj<List<InfoVO>> returnObj = new ReturnObj<List<InfoVO>>(list);
		return returnObj;
	}

	private String[] splitTagKeywords(String tagKeywords) {
		String split = Constants.TAG_KEYWORDS_SPLIT;
		if (StringUtils.isNotBlank(split)) {
			for (int i = 0, len = split.length(); i < len; i++) {
				tagKeywords = StringUtils.replace(tagKeywords,
						String.valueOf(split.charAt(i)), ",");
			}
		}
		return StringUtils.split(tagKeywords, ',');
	}
	@Autowired
	private TokenHolder tokenHolder;
	@Autowired
	protected PathResolver pathResolver;
	@Autowired
	private OperationLogService logService;
	@Autowired
	private HtmlService htmlService;
	@Autowired
	private AttributeService attributeService;
	@Autowired
	private MemberGroupService memberGroupService;
	@Autowired
	private NodeQueryService nodeQuery;
	@Autowired
	private InfoService service;
	@Autowired
	private InfoQueryService query;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private AttachmentRefService attachmentRefService;
}
